<?php
/**
 * Created by PhpStorm.
 * User: silov
 * Date: 15/6/24
 * Time: 15:13
 */
namespace Content\Model;

use Think\Cache\Driver\Memcache;
use Think\Model;
class ArticleModel extends Model {
    protected $tableName = "blog_article";

    public static $typeConfig = [
        1   => 'PHPER',
        2   => 'THINK',
        3   => 'GOODLIFE',
        4   => 'ABOUT',
    ];
    /**
     * @var string Api token redis key Pre_Uhash
     */
    const ARTICLE_MEMCACHE_ID_PREFIX = 'article_memcache_id_';

    /**
     * 根据ID获取文章详情
     * @param $id
     * @return mixed
     */
    public function getArticleById($id)
    {
//        $cache = Memcache::getInstance();
//        $key = self::ARTICLE_MEMCACHE_ID_PREFIX . $id;
//        $article = $cache->get($key);
//        if (empty($article)) {
            $article = $this->where(['id' => intval($id)])->find();
//            !empty($article) && $cache->set($key, $article);
//        }
        return $article;
    }

    /**
     * 发布&取消发布
     * @param $id
     * @return mixed
     */
    public function publish($id)
    {
        $article = $this->getArticleById($id);
        if (empty($article)) {
            return [
                'status'    => false,
                'code'      => 10000,
                'msg'       => '文章不存在!'
            ];
        }
        $data = [];
        $data['status'] = abs($article['status'] - 1);
        if ($article['status'] == 0 && $article['publish_time'] == 0) {
            $data['publish_time'] = time();
        }

        $res = $this->where(['id' => $id])->data($data)->save();
        if ($res) {
            return [
                'status'    => true,
                'code'      => 200,
                'msg'       => "操作成功!"
            ];
        } else {
            return [
                'status'    => false,
                'code'      => 10001,
                'msg'       => '更新失败,请重试!'
            ];
        }
    }

    /**
     * 文章推首页
     * @param $id
     * @return array
     */
    public function pushIndex($id)
    {
        $article = $this->getArticleById($id);
        if (empty($article)) {
            return [
                'status'    => false,
                'code'      => 10000,
                'msg'       => '文章不存在!'
            ];
        }
        if ($article['status'] == 0) {
            $this->publish($id);
        }
        //清理首页
        $this->where([])->data(['is_index' => 0])->save();
        $this->where(['id' => $id])->data(['is_index' => 1])->save();
        return [
            'status'    => true,
            'code'      => 200,
            'msg'       => '操作成功!'
        ];
    }

    public function getArticleByType($type)
    {
        return $this->where(['type' => intval($type)])->find();
    }
}